from sqlalchemy import Column, String, create_engine, Integer, Float, Date, MetaData, TEXT, event
from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base
from sqlalchemy.pool import NullPool
from sqlalchemy import text
from config import DATABASE_NAME, DATABASE_USER_NAME, DATABASE_USER_PASSWORD, DATABASE_HOST,DATABASE_PORT


class DbHandler(object):
    def __init__(self):
        con_url = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(DATABASE_USER_NAME,
                                                          DATABASE_USER_PASSWORD,
                                                          DATABASE_HOST,
                                                          DATABASE_PORT,
                                                          DATABASE_NAME)
        self.db_addr = con_url
        self.connect = None
        self.session = None
        self.engine = None

    def create_session(self):
        # 初始化数据库连接:
        # engine = create_engine(con_url, pool_size=100, pool_recycle=3600)
        self.engine = create_engine(self.db_addr, poolclass=NullPool)
        self.session = scoped_session(sessionmaker(bind=self.engine))
        self.connect = self.engine.connect()

    def close_session(self):
        self.session.close()
        self.connect.close()


# 创建DBSession类型:
Base = declarative_base()
metadata = MetaData()

if __name__ == '__main__':
    db = DbHandler()
    db.create_session()
    sql = text("SELECT * FROM JSL_bonds_alive")
    results = db.connect.execute(sql)
    for record in results:
        print(record)
    # r = redis.StrictRedis(host='localhost', password='alpine123', port=6379, db=0)

    # r.set('123456', 100.23)
    # r.flushdb()
    # print(float(r.get('123015_his_max')))
    # print(type(12.12))
    # Base.metadata.create_all(engine)
